<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <basic-information :info="infoList"></basic-information>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-receivingCodeScan>
              <input
                type="password"
                show-password
                autocomplete="off"
                auto-complete="off"
                readonly
                @focus="onFocusInputScan"
                class="inputRefScanHidden"
                v-bind:class="{ active: isActive }"
              />
              <el-input
                class="inputScan"
                ref="inputRefScan"
                placeholder="请扫码或输入条码"
                @keydown.enter.native="scanCode"
                v-model="filterInfo.scanInfo.code"
                @input="(e) => (filterInfo.scanInfo.code = validSe(e))"
                @blur="onBlurInputScan"
                :clearable="true"
              >
                <template #prepend>产品条码</template>
              </el-input>
            </template>
          </page-filter>
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :api="getUseExportDetailAll"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEvent"
                :spanMethod="objectSpanMethod"
                :isDynamic="true"
              >
                <template v-slot:col-contrastQty="scope">
                  <span>
                    {{ $fn.qtyFormatter(scope.row.outboundQty) }}
                    / {{ $fn.qtyFormatter(scope.row.storageQty) }}
                  </span>
                </template>
              </page-table>
            </el-form>
          </div>
          <select-product
            :query="productInfo.query"
            v-if="productInfo.visible"
            :api="productInfo.api"
            :show-stock="true"
            @callback="selectProductCallback"
            v-model:showDialog="productInfo.visible"
          />
          <SelectDepotStorage
            :query="depotStorageInfo.query"
            v-if="depotStorageInfo.visible"
            @callback="fillStorageProduct"
            v-model:showDialog="depotStorageInfo.visible"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="useReturnExportModify">
import {
  getUseExport,
  getUseExportDetailAll,
  getUseApplicationDetailAll,
  changeUseExport,
} from '@/api/use.js'
import { getDepotStorageProducts } from '@/api/stock'
import { getDepotStorageAll } from '@/api/stock.js'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id'])

const infoList = ref({
  data: {},
  fieldList: [
    { label: '领用人', value: 'createUserName', type: 'text' },
    { label: '领用部门', value: 'deptName', type: 'text' },
    { label: '领入仓库', value: 'storageDepotName', type: 'text' },
    { label: '领出仓库', value: 'exportDepotName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '出库日期', value: 'exportTime', type: 'text' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    statusNotIn: 'complete', //已完成的过滤
    useApplicationId: '',
    sort: 'product_id desc',
  },
  scanInfo: {
    code: '',
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    // {type: 'button', label: '删除产品', event: deleteProduct},
    // {type: 'input', label: '请扫描条码', value: 'code', event: scanCode}
    { type: 'slot', value: 'receivingCodeScan' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  data: [],
  fieldList: [
    { label: '产品名称', value: 'commonName' },
    { label: '产品编码', value: 'productCode' },
    { label: '生产厂家', value: 'brand' },
    { label: '规格', value: 'standard' },
    { label: '单位', value: 'unit' },
    {
      label: '申请数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    { label: '已出库/已入库', value: 'contrastQty', type: 'slot' },
    { label: '生产批号', value: 'batchNumber' },
    { label: '生产日期', value: 'productionDate' },
    { label: '失效日期', value: 'validityDate' },
    { label: '数量', value: 'exportQty', type: 'number', min: 0 },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '选择库存产品',
        event: selectDepotStorage,
        show: true,
      },
      { label: '删除', event: deleteOne, show: true },
    ],
  },
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  query: {
    deptId: '',
    idNotIn: '',
  },
  api: getDepotStorageProducts,
})
//选择库存产品
const depotStorageInfo = ref({
  visible: false,
  query: {},
  //当前选择的序号值
  currentIndex: null,
})
const selectRows = ref([])
const storageData = ref([])
const chooseIndex = ref([])
const useApplicationDetailList = ref([])
const isActive = ref(false)
const pos = ref(undefined)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => props.id,
  (value) => {
    loadData(value)
  },
  {
    immediate: true,
  }
)
watch(
  () => tableInfo.value.data,
  () => {
    getSpanArr(tableInfo.value.data)
  }
)
function loadData(newVal) {
  getUseExport(newVal).then((res) => {
    if (res.success) {
      infoList.value.data = res.data
      let params = {
        useApplicationId: res.data.useApplicationId,
        statusNot: 'complete',
      }
      getUseApplicationDetailAll(params).then((resp) => {
        if (resp && resp.success) {
          useApplicationDetailList.value = resp.data
        }
      })
    }
  })
  let query = { useExportId: newVal }
  getUseExportDetailAll(query).then((res) => {
    if (res.success) {
      tableInfo.value.data = res.data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      selectRows.value = data
      filterInfo.value.list[1].disabled = !selectRows.value.length
      break
  }
}
//添加产品,从使用申请明细中 赛选 状态为未完成的的明细列表(且不包含已有产品明细)
function addProduct() {
  productInfo.value.visible = true
  var productIds = useApplicationDetailList.value.map(function (detail) {
    return detail.productId
  })
  var existProductIds = tableInfo.value.data.map(function (detail) {
    return detail.productId
  })
  if (productIds.length > 0 && existProductIds.length > 0) {
    existProductIds.forEach((c) => {
      productIds.splice(
        productIds.findIndex((item) => item === c),
        1
      )
    })
  }
  productInfo.value.query.depotId = infoList.value.data.exportDepotId
  if (productIds.length > 0) {
    productInfo.value.query.productIds = productIds.join(',')
  } else {
    productInfo.value.query.productIds = ','
  }
}
function selectDepotStorage(row, index) {
  depotStorageInfo.value.query = {
    depotId: infoList.value.data.exportDepotId,
    productId: row.productId,
  }
  depotStorageInfo.value.currentIndex = index
  depotStorageInfo.value.visible = true
}
// 删除
function deleteOne(row, index) {
  tableInfo.value.data.splice(index, 1)
}
function selectProductCallback(data) {
  tableInfo.value.data = tableInfo.value.data.concat(data)
}
//增加相同产品+批号 数量
function increaseSameProductNumber(rows) {
  if (rows && rows.length != 0) {
    rows.forEach((row) => {
      tableInfo.value.data.some((item, i) => {
        if (
          item.productCode == row.productCode &&
          item.batchNumber === row.batchNumber
        ) {
          item.exportQty = item.exportQty === null ? 1 : item.exportQty + 1
          rows.splice(i, 1)
          return true
        }
      })
    })
  }
}
//填充库存产品
function fillStorageProduct(row) {
  increaseSameProductNumber(row)
  let arr = tableInfo.value.data.slice(0)
  let data = arr[depotStorageInfo.value.currentIndex]
  let newData = []
  if (row.length) {
    row.forEach((item) => {
      let addData = {
        batchNumber: item.batchNumber,
        productionDate: item.productionDate,
        validityDate: item.validityDate,
        price: item.price,
        code: item.code,
        depotStorageId: item.id,
        exportQty: 1,
      }
      newData.push({ ...data, ...addData })
    })
  }
  newData.unshift(depotStorageInfo.value.currentIndex + 1, 0)
  ;[].splice.apply(arr, newData)
  if (!data.hasOwnProperty('batchNumber') && !data.batchNumber) {
    arr.splice(depotStorageInfo.value.currentIndex, 1)
  }
  tableInfo.value.data = arr
}
function getSpanArr(data) {
  spanArr.value = []
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr.value.push(1)
      pos.value = 0
    } else {
      if (data[i].productCode === data[i - 1].productCode) {
        spanArr.value[pos.value] += 1
        spanArr.value.push(0)
      } else {
        spanArr.value.push(1)
        pos.value = i
      }
    }
  }
}
function save() {
  let type = 'create'
  let api = changeUseExport
  let passValid = false
  if (tableInfo.value.data.length === 0) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '出库明细不能为空',
    })
    return
  } else {
    tableInfo.value.data.some((item) => {
      if (item.depotStorageId) {
        passValid = true
      }
      if (passValid) {
        return true
      }
    })
    if (!passValid) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请选择出库产品数据',
      })
    }
  }
  if (passValid) {
    let data = {
      useExport: infoList.value.data,
      useExportDetails: tableInfo.value.data,
    }
    proxy
      .$handleAPI(type, api, data)
      .then((res) => {
        if (res.success) {
          showDialog.value = false
          emits('returnModify')
        }
      })
      .catch((error) => {
        proxy.$message({
          duration: 3500,
          type: 'error',
          showClose: true,
          message: error,
        })
      })
  }
}
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  // console.log( spanArr.value, rowIndex, columnIndex)
  if (columnIndex >= 1 && columnIndex <= 7) {
    const _row = spanArr.value[rowIndex]
    const _col = _row > 0 ? 1 : 0
    return {
      rowspan: _row,
      colspan: _col,
    }
  }
}
//扫码出库
function onFocusInputScan() {
  setTimeout(() => {
    proxy.$refs.inputRefScan.focus()
    isActive.value = true
    document
      .getElementsByClassName('inputRefScanHidden')[0]
      .removeAttribute('readonly')
  }, 300)
}
function onBlurInputScan() {
  isActive.value = false
}
function scanCode() {
  let code = event.target.value || undefined
  if (!code) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请扫描二维码',
    })
    return
  }
  proxy.$refs.inputRefScan.value = code
  let query = {
    depotId: infoList.value.data.exportDepotId,
    code: encodeURIComponent(filterInfo.value.scanInfo.code),
  }
  getDepotStorageAll(query).then((res) => {
    if (res.success) {
      if (res.data.length) {
        var addData = res.data[0]
        //查找存在的数据
        var find = false
        tableInfo.value.data.some((item, i) => {
          if (item.productCode === addData.productCode) {
            depotStorageInfo.value.currentIndex = i
            find = true
            return true
          }
        })
        if (find) {
          fillStorageProduct([addData])
        } else {
          proxy.$message({
            duration: 3500,
            type: 'warning',
            showClose: true,
            message: '当前扫码编号【' + query.code + '】不属于本次领用产品',
          })
        }
      } else {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: '当前扫码编号【' + query.code + '】不在领用仓库',
        })
      }
    }
  })
}
//删除产品
function deleteProduct(data = undefined) {
  if (data) {
    tableInfo.value.data = tableInfo.value.data.filter((row) => data !== row)
  } else {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => !tableInfo.value.selections.includes(row)
    )
  }
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}
.inputScan {
  ime-mode: disabled;
}
.active {
  display: none;
}
</style>
